
<template>
  <div class="dashboard-wrapper">
    <div class="dashboard-header-actions">
      <el-button type="primary" size="small" @click="refreshData">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
      <el-button type="primary" size="small" @click="switchToTestOrder">
        <el-icon><Document /></el-icon>
        测试单管理
      </el-button>
      <el-button size="small" @click="exportDashboardData">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>
    <div class="dashboard-content">
        <div class="data-overview">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6">
              <div class="data-card">
                <el-icon class="data-icon"><Management /></el-icon>
                <div class="data-info">
                  <div class="data-value">{{ dashboardData.totalProducts }}</div>
                  <div class="data-label">产品总数</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <div class="data-card">
                <el-icon class="data-icon"><Document /></el-icon>
                <div class="data-info">
                  <div class="data-value">{{ dashboardData.totalApplications }}</div>
                  <div class="data-label">测试申请</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <div class="data-card">
                <el-icon class="data-icon"><Check /></el-icon>
                <div class="data-info">
                  <div class="data-value">{{ dashboardData.totalTests }}</div>
                  <div class="data-label">测试任务</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <div class="data-card">
                <el-icon class="data-icon"><Warning /></el-icon>
                <div class="data-info">
                  <div class="data-value">{{ dashboardData.totalDefects }}</div>
                  <div class="data-label">缺陷总数</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :xs="24">
            <el-card class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <span>预集成测试待办</span>
                  <el-button type="text" size="small" @click="viewAllTodoItems">查看全部</el-button>
                </div>
              </template>
              <div v-if="todoItems.length > 0" class="todo-list">
                <el-table :data="todoItems" stripe style="width: 100%">
                  <el-table-column prop="todoId" label="待办ID" width="120"></el-table-column>
                  <el-table-column prop="title" label="待办标题"></el-table-column>
                  <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                  <el-table-column prop="deadline" label="截止日期" width="150">
                    <template #default="scope">
                      <span :class="{ 'deadline-warning': isDeadlineWarning(scope.row.deadline) }">
                        {{ scope.row.deadline }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" fixed="right">
                    <template #default="scope">
                      <el-button type="primary" size="small" @click="handleTodoItem(scope.row)">处理</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-else class="empty-todos">
                <el-empty description="暂无待办事项" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :xs="24">
            <el-card class="dashboard-card">
              <template #header>
                <div class="card-header">
                  <span>个人任务清单</span>
                  <el-button type="text" size="small" @click="viewAllPersonalTasks">查看全部</el-button>
                </div>
              </template>
              <div class="task-search" style="margin-bottom: 15px;">
                <el-input v-model="searchKeyword" placeholder="搜索任务" prefix-icon="Search" />
              </div>
              <div v-if="filteredTasks.length > 0" class="task-list">
                <el-table :data="filteredTasks" stripe style="width: 100%">
                  <el-table-column prop="taskId" label="任务ID" width="120"></el-table-column>
                  <el-table-column prop="taskName" label="任务名称"></el-table-column>
                  <el-table-column prop="productName" label="所属产品" width="150"></el-table-column>
                  <el-table-column prop="taskType" label="任务类型" width="120">
                    <template #default="scope">
                      <el-tag :type="getTaskTypeTag(scope.row.taskType)">{{ scope.row.taskType }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="截止日期" width="150"></el-table-column>
                  <el-table-column label="操作" width="120" fixed="right">
                    <template #default="scope">
                      <el-button type="primary" size="small" @click="handleTask(scope.row)">处理</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-else class="empty-tasks">
                <el-empty description="暂无任务" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <div v-if="hasAdminPermission" style="margin-bottom: 20px;">
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :xs="24">
              <el-card class="dashboard-card metrics-card">
                <template #header>
                  <div class="card-header">
                    <span>整体度量视图</span>
                  </div>
                </template>
                <div class="metrics-content">
                  <el-row :gutter="20">
                    <el-col :xs="24" :sm="12" :md="6">
                      <div class="metric-item">
                        <div class="metric-value">{{ metricsData.preIntegrationProducts }}</div>
                        <div class="metric-label">预集成产品数</div>
                      </div>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="6">
                      <div class="metric-item">
                        <div class="metric-value">{{ metricsData.pendingApplications }}</div>
                        <div class="metric-label">待处理申请</div>
                      </div>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="6">
                      <div class="metric-item">
                        <div class="metric-value">{{ metricsData.completedTests }}</div>
                        <div class="metric-label">已完成测试</div>
                      </div>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="6">
                      <div class="metric-item">
                        <div class="metric-value">{{ metricsData.openDefects }}</div>
                        <div class="metric-label">未解决缺陷</div>
                      </div>
                    </el-col>
                  </el-row>

                  <div class="version-progress">
                    <h4>产品各版本提测进度</h4>
                    <el-table :data="versionProgress" stripe style="width: 100%;">
                      <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                      <el-table-column prop="versionName" label="版本" width="120"></el-table-column>
                      <el-table-column prop="testProgress" label="测试进度" width="180">
                        <template #default="scope">
                          <el-progress :percentage="scope.row.testProgress" :status="getProgressStatus(scope.row.testProgress)" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="defectRate" label="缺陷率" width="100">
                        <template #default="scope">
                          <span :class="{ 'defect-rate-high': scope.row.defectRate > 5 }">
                            {{ scope.row.defectRate }}%
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="status" label="状态" width="100">
                        <template #default="scope">
                          <el-tag :type="getStatusTag(scope.row.status)">{{ scope.row.status }}</el-tag>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Management, Document, Check, Warning, Refresh, Download, Search } from '@element-plus/icons-vue'
import MessageService from '@/utils/MessageService.js'

const messageService = MessageService
const router = useRouter()
const route = useRoute()

const dashboardData = ref({
  totalProducts: 0,
  totalApplications: 0,
  totalTests: 0,
  totalDefects: 0
})

const personalTasks = ref([])
const searchKeyword = ref('')
const todoItems = ref([])
const metricsData = ref({
  preIntegrationProducts: 0,
  pendingApplications: 0,
  completedTests: 0,
  openDefects: 0
})
const versionProgress = ref([])
const userInfo = ref({
  role: 'TESTER',
  roles: ['TESTER']
})

const hasAdminPermission = computed(() => {
  return userInfo.value && userInfo.value.roles && 
    (userInfo.value.roles.includes('ADMIN') || userInfo.value.roles.includes('PRODUCT_MANAGER'))
})

const switchToTestOrder = () => {
  router.push('/dashboard/test-order/manage')
}

onMounted(() => {
  refreshData()
  fetchUserInfo()
})

const refreshData = async () => {
  try {
    await Promise.all([
      fetchDashboardData(),
      fetchPersonalTasks(),
      fetchTodoItems(),
      fetchMetricsData()
    ])
    messageService.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    messageService.error('数据刷新失败，请稍后重试')
  }
}

const fetchDashboardData = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    dashboardData.value = {
      totalProducts: 24,
      totalApplications: 18,
      totalTests: 145,
      totalDefects: 89
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    messageService.error('获取仪表盘数据失败')
    dashboardData.value = {
      totalProducts: 0,
      totalApplications: 0,
      totalTests: 0,
      totalDefects: 0
    }
  }
}

const fetchPersonalTasks = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 400))
    personalTasks.value = [
      { taskId: 'TASK-2025001', taskName: '验证用户登录模块功能', productName: '用户管理系统', taskType: '功能测试', dueDate: '2025-01-10' },
      { taskId: 'TASK-2025002', taskName: '性能测试电商首页加载速度', productName: '电商平台', taskType: '性能测试', dueDate: '2025-01-12' },
      { taskId: 'TASK-2025003', taskName: '安全测试支付接口', productName: '支付系统', taskType: '安全测试', dueDate: '2025-01-15' },
      { taskId: 'TASK-2025004', taskName: '兼容性测试数据分析图表', productName: '数据分析系统', taskType: '兼容性测试', dueDate: '2025-01-18' }
    ]
  } catch (error) {
    console.error('获取个人任务失败:', error)
    messageService.error('获取个人任务失败')
    personalTasks.value = []
  }
}

const fetchTodoItems = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 400))
    todoItems.value = [
      { todoId: 'TODO-2025001', title: '审核用户管理系统v2.0预集成测试申请', productName: '用户管理系统', deadline: '2025-01-15' },
      { todoId: 'TODO-2025002', title: '确认电商平台v3.5集成测试环境', productName: '电商平台', deadline: '2025-01-12' },
      { todoId: 'TODO-2025003', title: '处理支付系统v1.8测试申请反馈', productName: '支付系统', deadline: '2025-01-10' },
      { todoId: 'TODO-2025004', title: '评审数据分析系统预集成测试方案', productName: '数据分析系统', deadline: '2025-01-20' }
    ]
  } catch (error) {
    console.error('获取预集成测试待办失败:', error)
    messageService.error('获取预集成测试待办失败')
    todoItems.value = []
  }
}

const fetchMetricsData = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    metricsData.value = {
      preIntegrationProducts: 12,
      pendingApplications: 8,
      completedTests: 45,
      openDefects: 23
    }
    
    versionProgress.value = [
      { productName: '用户管理系统', versionName: 'v2.0', testProgress: 85, defectRate: 3.2, status: '进行中' },
      { productName: '电商平台', versionName: 'v3.5', testProgress: 60, defectRate: 5.8, status: '进行中' },
      { productName: '支付系统', versionName: 'v1.8', testProgress: 95, defectRate: 2.1, status: '即将完成' },
      { productName: '数据分析系统', versionName: 'v1.0', testProgress: 40, defectRate: 7.5, status: '进行中' },
      { productName: '内容管理系统', versionName: 'v3.2', testProgress: 100, defectRate: 1.8, status: '已完成' }
    ]
  } catch (error) {
    console.error('获取度量数据失败:', error)
    messageService.error('获取度量数据失败')
    metricsData.value = {
      preIntegrationProducts: 0,
      pendingApplications: 0,
      completedTests: 0,
      openDefects: 0
    }
    versionProgress.value = []
  }
}

const fetchUserInfo = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const parsedUserInfo = JSON.parse(userInfoStr)
      userInfo.value = {
        ...parsedUserInfo,
        roles: parsedUserInfo.roles || ['TESTER']
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = {
      role: 'TESTER',
      roles: ['TESTER']
    }
  }
}

const getTaskTypeTag = (taskType) => {
  const typeMap = {
    '功能测试': 'primary',
    '性能测试': 'warning',
    '安全测试': 'danger',
    '兼容性测试': 'info'
  }
  return typeMap[taskType] || 'default'
}

const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success'
  if (progress >= 60) return 'warning'
  return 'exception'
}

const getStatusTag = (status) => {
  const statusMap = {
    '进行中': 'primary',
    '即将完成': 'warning',
    '已完成': 'success',
    '已暂停': 'danger',
    '未开始': 'info'
  }
  return statusMap[status] || 'default'
}

const isDeadlineWarning = (deadline) => {
  try {
    const today = new Date()
    const deadlineDate = new Date(deadline)
    const diffDays = Math.ceil((deadlineDate - today) / (1000 * 60 * 60 * 24))
    return diffDays <= 3 && diffDays >= 0
  } catch (error) {
    return false
  }
}

const filteredTasks = computed(() => {
  if (!searchKeyword.value) {
    return personalTasks.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return personalTasks.value.filter(task => 
    task.taskName.toLowerCase().includes(keyword) ||
    task.productName.toLowerCase().includes(keyword) ||
    task.taskType.toLowerCase().includes(keyword)
  )
})

const handleTask = (task) => {
  messageService.info(`处理任务: ${task.taskName}`)
}

const viewAllPersonalTasks = () => {
  messageService.info('查看全部个人任务')
}

const handleTodoItem = (todo) => {
  messageService.info(`处理待办: ${todo.title}`)
}

const viewAllTodoItems = () => {
  messageService.info('查看全部待办事项')
}

const exportDashboardData = () => {
  messageService.confirm('确定要导出仪表盘数据吗？', '提示')
    .then(() => {
      setTimeout(() => {
        messageService.success('数据导出成功')
      }, 1000)
    })
    .catch(() => {
      messageService.info('已取消导出')
    })
}
</script>

<style scoped>
.dashboard-wrapper {
  padding: 20px;
}

.dashboard-header-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.dashboard-content {
  min-height: calc(100vh - 200px);
}

.dashboard-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-overview {
  margin-bottom: 30px;
}

.data-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  height: 100px;
  transition: all 0.3s;
}

.data-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.data-info {
  flex: 1;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.data-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.data-icon {
  font-size: 32px;
  color: #409EFF;
  margin-right: 16px;
}

.task-search {
  margin-bottom: 15px;
}

.empty-todos, .empty-tasks {
  padding: 40px 0;
  text-align: center;
}

.deadline-warning {
  color: #f56c6c;
  font-weight: bold;
}

.defect-rate-high {
  color: #f56c6c;
  font-weight: bold;
}

.metrics-card {
  margin-bottom: 20px;
}

.metrics-content {
  padding: 20px 0;
}

.metric-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.metric-item:hover {
  background-color: #e6f7ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
}

.metric-label {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.version-progress {
  margin-top: 30px;
}

.version-progress h4 {
  margin-bottom: 15px;
  color: #333;
}

@media screen and (max-width: 768px) {
  .dashboard-content {
    padding-top: 10px;
  }
  
  .todo-list, .task-list {
    height: auto;
  }
  
  .data-overview {
    margin-bottom: 20px;
  }
  
  .data-card {
    height: auto;
    min-height: 80px;
    padding: 15px;
  }
  
  .metric-item {
    padding: 15px 10px;
    margin-bottom: 10px;
  }
  
  .metric-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .version-progress {
    margin-top: 20px;
  }
}
</style>
